package io.esirong

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Looper
import android.os.Process
import android.text.TextUtils
import android.view.View
import java.io.BufferedReader
import java.io.File
import java.io.FileReader


/**
 * 默认的工具类
 * <P>将暂时不能分类的静态工具方法存放在这里。直到可以确认分类再作移动安排。
 * Created by 黄嵘才(HuangRc) on 2019/9/23.
 */

/** Returns `true` if called on the main thread（UI Thread), `false` otherwise.  */
fun isOnMainThread(): Boolean {
    return Looper.myLooper() == Looper.getMainLooper()
}

/** Returns `true` if called on a background thread, `false` otherwise.  */
fun isOnBackgroundThread(): Boolean {
    return !isOnMainThread()
}

/**
 * 获取当前进程的名称
 */
fun getProcessName(): String? {
    var mBufferedReader: BufferedReader? = null
    try {
        val file = File("/proc/" + Process.myPid() + "/" + "cmdline")
        mBufferedReader = BufferedReader(FileReader(file))
        return mBufferedReader.readLine()
    } catch (e: Exception) {
        e.printStackTrace()
        return null
    } finally {
        mBufferedReader?.close()
    }

}

/**
 * 判断是不是应用的进程（通过包名的匹配来判断，用来于区分多进程服务的）
 *
 * @param context 本应用进程的上下文 [Context]
 * @return true 是应用的进程
 */
fun isMainProcess(context: Context): Boolean {
    //判断进程名，保证只有主进程运行
    return !TextUtils.isEmpty(getProcessName()) && getProcessName() == context.packageName

}

/**
 * 打开拔号盘打电话
 *
 * @param context     [Context]
 * @param phoneNumber 电话号码
 */
fun dialPhone(context: Context, phoneNumber: String) {
    val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phoneNumber"))
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    context.startActivity(intent)
}

/**
 * 把集合组合为一条数据（其中元素间用分隔符）
 */
fun join(iterator: Iterator<*>, separator: String?): String? {
    var separator = separator
    if (separator == null) {
        separator = ""
    }
    val buf = StringBuilder(256)
    while (iterator.hasNext()) {
        buf.append(iterator.next())
        if (iterator.hasNext()) {
            buf.append(separator)
        }
    }
    return buf.toString()
}


/**
 *隐去系统的状态条
 * 界面头的状态条，状态栏
 * @param activity [Activity]
 */
fun hideSysBar(activity: Activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        var uiOptions: Int = activity.getWindow().getDecorView().getSystemUiVisibility()
        uiOptions = uiOptions or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        uiOptions = uiOptions or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        uiOptions = uiOptions or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        uiOptions = uiOptions or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        uiOptions = uiOptions or View.SYSTEM_UI_FLAG_FULLSCREEN
        uiOptions = uiOptions or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        activity.getWindow().getDecorView().setSystemUiVisibility(uiOptions)
    }
}

